<template>
  <!-- 角色管理 -->
  <div class="role">
    <div class="role-left">
      <div class="add-role-btn" @click="addRoleBtnClick">
        <img src="@/assets/imgs/role/addcion.svg" alt="" />
        创建角色
      </div>
      <div
        v-for="item in roleList"
        :key="item.id"
        class="role-itme"
        :class="{ 'active-item': roleItem.id == item.id }"
        @click="roleClick(item)"
      >
        <!-- <img class="icon" :src="`/src/assets/imgs/role/${item.icon}.png`" /> -->
        <i class="iconfont avat" :class="item.icon"></i>
        {{ item.name }}
      </div>
    </div>
    <div class="role-right">
      <div class="tabs">
        <div
          v-for="item in tabsList"
          :key="item.id"
          class="tab-item"
          :class="{ 'active-tab': activeTab == item.id }"
          @click="activeTab = item.id"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="role-container" v-show="activeTab == 1">
        <div class="content">
          <span class="describe">
            <el-tooltip
              effect="dark"
              :content="roleItem.name + '：' + roleItem.describe"
              placement="top"
              popper-class="tooltips"
              :show-arrow="false"
            >
              {{ roleItem.name }}：{{ roleItem.describe }}
            </el-tooltip>
          </span>
          <span class="save" @click="save">保存</span>
        </div>
        <div class="role-contanier">
          <div class="check-all">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handlerChange($event)"
            ></el-checkbox>
            全选
          </div>
          <div class="item">
            <myCheckbox
              :authorityList="authorityList"
              :num="num"
              @selfCheck="selfCheck"
            ></myCheckbox>
          </div>
        </div>
      </div>
      <div class="role-container" v-show="activeTab == 2">
        <div class="content">
          <span> {{ roleItem.name }}：{{ roleItem.describe }}</span>
          <span class="save" @click="save">添加用户</span>
        </div>
        <div class="user-list">
          <div v-for="item in newUserList" class="user-item">
            {{ item.userName }}
          </div>
        </div>
      </div>
    </div>
    <!-- 添加角色 -->
    <el-dialog
      v-model="addRoleDialogVisible"
      title="创建角色"
      width="500"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="addRoleRuleForm"
          :rules="addRoleRules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="角色名称" prop="roleName" :error="errorMsg1">
            <el-input
              v-model="addRoleRuleForm.roleName"
              clearable
              @blur="checkMobile"
            />
          </el-form-item>
          <el-form-item label="角色描述" prop="describe">
            <el-input v-model="addRoleRuleForm.describe" clearable />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="addRole(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, inject } from "vue";
import { useRoute, useRouter } from "vue-router";
import myCheckbox from "./myCheckbox.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getAuthorityListAPI,
  getRoleListAPI,
  roleCheckAPI,
  addRoleAPI,
  assignPermissionsAPI,
  getUserListAPI,
} from "@/api/user";
const props = defineProps({});

let emit = defineEmits([""]);

// 角色列表
const roleList = ref([]);
// 获取角色列表
async function getRoleList() {
  try {
    let res = await getRoleListAPI();
    console.log(res, "角色列表");
    roleList.value = res.data;
    roleClick(roleList.value[0]);
  } catch (error) {
    console.log(error);
  }
}

// /点击某个角色，获取当前角色信息
const roleItem = ref({});
// 根据角色的全选，进行反显
function getDefaultAuthority(arr, ids) {
  arr.forEach((v) => {
    if (v.children && v.children.length) {
      getDefaultAuthority(v.children, ids);
    }
    if (ids.includes(v.id)) {
      v.checked = true;
    } else {
      v.checked = false;
    }
  });
}
// 用户列表
const userList = ref([]);
const newUserList = ref([]);
async function getUserList() {
  try {
    let res = await getUserListAPI();
    console.log(res);
    userList.value = res.data.data;
  } catch (error) {
    console.log(error);
  }
}
// 点击角色
const roleClick = (item) => {
  roleItem.value = item;
  getDefaultAuthority(authorityList.value, item.authorityList);
  selfCheck();

  newUserList.value = userList.value.filter((v) => v.role == item.id);
  console.log(newUserList.value, "用户列表");
};

// 右侧
const tabsList = [
  {
    name: "角色权限",
    id: 1,
  },
  {
    name: "角色用户",
    id: 2,
  },
];
const activeTab = ref(1);
const num = ref(0);

// 显示选中时的条件：checked == true;isIndeterminate == false
// 显示不选中时的条件: checked == false ; isIndeterminate == false
// 显示半选时的条件: checked == false; isIndeterminate == true

// 权限列表
const authorityList = ref();
// 获取权限
async function getAuthorityList() {
  try {
    let res = await getAuthorityListAPI();
    authorityList.value = res.data;
    console.log(res, "权限列表");
  } catch (error) {
    console.log(error);
  }
}

// 全选反选
const checkAll = ref(false);
const isIndeterminate = ref(false);
function recursionCheck(arr, flag) {
  arr.forEach((v) => {
    if (v.children && v.children.length > 0) {
      recursionCheck(v.children, flag);
    }
    v.checked = flag;
  });
}
// 全选
const handlerChange = (e) => {
  recursionCheck(authorityList.value, e);
  selfCheck();
};

// 根据子项勾选状态，返回父项勾选状态
function updateParent(nodes) {
  nodes.forEach((node) => {
    if (node.children && node.children.length) {
      updateParent(node.children);
      // 存在子节点，则根据子节点状态更新当前节点状态
      const allChecked = node.children.every((child) => child.checked);
      const noneChecked = node.children.every((child) => !child.checked);
      node.checked = allChecked;
      node.isIndeterminate = !allChecked && !noneChecked;
    }
  });
}

const selfCheck = () => {
  //
  console.log("有变化");
  updateParent(authorityList.value);
  const allChecked = authorityList.value.every((child) => child.checked);
  const noneChecked = authorityList.value.every((child) => !child.checked);
  checkAll.value = allChecked;
  isIndeterminate.value = !allChecked && !noneChecked;
};

// 获取选中的id
function getIds(arr, ids) {
  arr.forEach((v) => {
    if (v.children && v.children.length > 0) {
      getIds(v.children, ids);
    } else {
      if (v.checked) {
        ids.push(v.id);
      }
    }
  });
  return ids;
}
// 分配权限
const save = async () => {
  let ids = getIds(authorityList.value, []);
  console.log(ids);
  try {
    let res = await assignPermissionsAPI({
      roleId: roleItem.value.id,
      authorityList: ids,
    });
    // console.log(res);
    ElMessage({
      showClose: true,
      message: res.message,
      type: "success",
    });
  } catch (error) {
    console.log(error);
  }
};
// 新建角色
// 校验用户名是否已被占用
// 添加/编辑用户校验手机号码是否重复
const addRoleBtnClick = () => {
  console.log(222);
  addRoleDialogVisible.value = true;
};
const errorMsg1 = ref("");
async function checkMobile() {
  errorMsg1.value = ""; //校验前需情况错误信息
  if (addRoleRuleForm.value.rolwName != "") {
    let res = await roleCheckAPI({ roleName: addRoleRuleForm.value.roleName });
    console.log(res, 888);
    if (res.data.respDesc) {
      errorMsg1.value = ""; //后台返回错误信息
    } else {
      errorMsg1.value = "该账号已被注册"; //后台返回错误信息
    }
  }
}
const ruleFormRef = ref(null);
const addRoleDialogVisible = ref(false);
const handleClose = () => {
  addRoleDialogVisible.value = false;
};
const addRoleRuleForm = ref({});
const addRoleRules = {
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  describe: [{ required: true, message: "请输入角色描述户", trigger: "blur" }],
};

// 添加角色
const addRole = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      let res = await addRoleAPI(addRoleRuleForm.value);
      getRoleList();
      addRoleDialogVisible.value = false;
      formEl.resetFields();
    } else {
      console.log("error submit!", fields);
    }
  });
};
onMounted(() => {
  getUserList();
  getAuthorityList();
  getRoleList();
});
</script>
<style lang="scss">
@keyframes move {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(0);
  }
}

.role {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  animation: move 0.2s ease-in-out;
  display: flex;

  .role-left {
    .item {
      width: 240px;
      height: 60px;
      line-height: 60px;
      font-size: 14px;
      color: #fcfdff;
      margin-top: 20px;
    }
    width: 300px;
    height: 100%;

    display: flex;
    flex-direction: column;

    align-items: center;
    .add-role-btn {
      background: url(@/assets/imgs/role/addrole.svg) no-repeat;
      background-size: 100% 100%;
      text-align: center;

      @extend .item;
      img {
        vertical-align: middle;
      }
    }
  }
  .role-itme {
    @extend .item;
    padding: 0 20px;
    &:hover {
      background-color: #1a74ff63;
    }
    .avat {
      display: inline-block;
      width: 30px;
      height: 30px;
      // vertical-align: middle;
      font-size: 24px;
      color: #169bd5;
    }
  }
  .active-item {
    background-color: #235096;

    border-right: 10px solid #1a74ff;
  }
  .role-right {
    width: calc(100% - 300px);
    height: 100%;

    border: 1px solid #fff;
    .tabs {
      height: 32px;
      display: flex;
      .tab-item {
        margin-right: 1px;
        width: 200px;
        line-height: 32px;
        text-align: center;
        background: rgb(108, 108, 108);
        font-size: 14px;
      }
      .active-tab {
        background: #2698c8;
      }
    }
    .role-container {
      width: 100%;
      height: calc(100% - 32px);
      .content {
        height: 40px;
        padding: 0 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .describe {
          width: 88%;
          height: 40px;
          overflow: hidden;
          font-size: 14px;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .save {
          display: inline-block;
          width: 120px;
          height: 40px;
          line-height: 40px;
          font-size: 14px;
          background: #169bd5;
          text-align: center;
          border-radius: 5px;
        }
      }
      .role-contanier {
        width: calc(100% - 10px);
        height: calc(100% - 92px);
        margin: 10px 0 0px 10px;
        overflow: hidden;
        overflow-y: auto;
        box-sizing: border-box;

        .check-all {
          height: 30px;
        }
        .item {
          height: calc(100% - 30px);
          width: 100%;
        }
      }
      .user-list {
        height: calc(100% - 40px);
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        overflow: hidden;
        overflow-y: auto;
        .user-item {
          margin-left: 10px;
        }
      }
    }
  }
}
:deep(.el-popper) {
  .el-popper .is-dark {
    width: 200px !important;
    color: red !important;
    background: red;
  }
}

.tooltips {
  max-width: 1200px !important;
  background: #169bd5 !important;
}
</style>
